<template>
  <div class="container">
 <!-- 表单 -->
 <el-card style="margin: 10px ">
   <!-- 头部说明 -->
   <el-row type="flex" class="row-bg" justify="space-between" >
       <span style="font-size: 12px; color: pink;">说明：目前支持学科和关键字条件筛选</span>
       <el-button @click="$router.push({path:'new'})" size="small" type="success" icon="el-icon-edit" >新增试题</el-button>
   </el-row>
   <!-- 表单 -->
   <el-form
    :model="form"
    ref="searchForm"
    size="small" label-width="80px">
      <!-- 第一行 -->
      <el-row>
      <el-col :span="6">
        <el-form-item label="学科" prop="subjectName">
          <el-select
            class="form-select"
            v-model="form.subjectName"
            placeholder="请选择"
          >
            <el-option
            v-for="item in FiltrateRender.Subject"
            :key="item.id"
            :label="item.subjectName"
            :value="item.subjectName"
             ></el-option>
          </el-select>
      </el-form-item>

      </el-col>
      <el-col :span="6">
        <el-form-item label="二级目录" prop="directoryName">
          <el-select
            class="form-select"
            v-model="form.directoryName"
            placeholder="请选择"
          >
          <el-option
          v-for="item in FiltrateRender.Directory"
          :key="item.id"
          :label="item.directoryName"
          :value="item.directoryName"
          ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="标签" prop="tagName">
          <el-select
            class="form-select"
            v-model="form.tagName"
            placeholder="请选择"
          >
            <el-option
            v-for="item in FiltrateRender.Tags"
            :key="item.id"
            :label="item.tagName"
            :value="item.tagName"></el-option>
          </el-select>
        </el-form-item>
    </el-col>
      <el-col :span="6">
        <el-form-item label="关键字" prop="question">
          <el-input v-model="form.question" placeholder="根据提干搜索"></el-input>
        </el-form-item>
    </el-col>
    </el-row>

    <!-- 第二行 -->
    <el-row>
      <el-col :span="6">
        <el-form-item label="试题类型" prop="types">
          <el-select
            class="form-select"
            v-model="form.types"
            placeholder="请选择"
          >
            <el-option
            v-for="item in FiltrateRender.questionType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            ></el-option>
          </el-select>
      </el-form-item>

      </el-col>
      <el-col :span="6">
        <el-form-item label="难度" prop="difficulty">
          <el-select
            class="form-select"
            no-data-text="无数据"
            v-model="form.difficulty"
            placeholder="请选择"
          >
          <el-option
            v-for="item in FiltrateRender.difficulty"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            ></el-option>

          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="方向" prop="direction">
          <el-select
            class="form-select"
            v-model="form.direction"
            placeholder="请选择"
          >
          <el-option
            v-for="item,index in FiltrateRender.direction"
            :key="index"
            :label="item"
            :value="index "
            ></el-option>
          </el-select>
        </el-form-item>
    </el-col>
      <el-col :span="6">
        <el-form-item label="录入人" prop="user">
          <el-select
            class="form-select"
            v-model="form.user"
            placeholder="请选择"
          >
          <el-option
            v-for="item in FiltrateRender.user"
            :key="item.id"
            :label="item.permission_group_title"
            :value="item.id "
            ></el-option>
          </el-select>
        </el-form-item>
    </el-col>
    </el-row>

    <el-row>
      <el-col :span="6">
        <el-form-item label="题目备注" prop="TitleNotes">
        <el-input v-model="form.TitleNotes"></el-input>
      </el-form-item>

      </el-col>
      <el-col :span="6">
        <el-form-item label="企业简称" prop="shortened">
         <el-input v-model="form.shortened"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="城市" prop="provinces" >
          <el-select
            style="width: 48%; margin-right: 2%;"
            class="form-select"
            v-model="form.provinces"
            placeholder="请选择"
          >
          <el-option
            v-for="item,index in FiltrateRender.provinces"
            :key="index"
            :label="item"
            :value="item "
            ></el-option>
          </el-select>

          <el-select
             style="width: 50%;"
             class="form-select"
             v-model="form.citys"
             placeholder="请选择"
          >
          <el-option
            v-for="item,index in FiltrateRender.citys"
            :key="index"
            :label="item"
            :value="index "
            ></el-option>
          </el-select>
        </el-form-item>
    </el-col>
    <el-col  :span="6" style="text-align: right;">
      <el-button size="mini" @click="resetForm('searchForm')">清除</el-button>
      <el-button type="primary" size="mini" @click="search">搜索</el-button>
    </el-col>
    </el-row>
    </el-form>
  <!-- 状态说明 -->
   <el-tabs  type="card"
             @tab-click="handleClick"
             v-model="activeName"
   >
    <el-tab-pane
            label="全部"
            name="first"
      >
      <el-alert
              style="margin-bottom: 15px;"
              :title="`数据一共${String(question.length)}条`"
              type="info"
              show-icon>

     </el-alert>
  </el-tab-pane>

    <el-tab-pane label="待审核" name="second">
        <el-alert
              style="margin-bottom: 15px;"
              :title="`数据一共${String(question.length)}条`"
              type="info"
              show-icon>
        </el-alert>
    </el-tab-pane>

    <el-tab-pane label="已审核" name="third">
         <el-alert
              style="margin-bottom: 15px;"
              :title="`数据一共${String(question.length)}条`"
              type="info"
              show-icon>
         </el-alert>
    </el-tab-pane>

    <el-tab-pane label="已拒绝" name="fourth">
        <el-alert
              style="margin-bottom: 15px;"
              :title="`数据一共${String(question.length)}条`"
              type="info"
              show-icon>
      </el-alert>
   </el-tab-pane>

  </el-tabs>

     <!-- 表格 -->
      <el-table
                :header-cell-style="{
                background:'#fafafa',color:'#909399',boxShadow:' 0 0 10px 10px rgb(250, 248, 248) '}"
                :data="question"
                style="wibtn:100%"
                >
      <el-table-column
                label="考试编号"
                prop="number"
                >
          </el-table-column>

      <el-table-column
                label="学科"
                prop="subject"
                >
              </el-table-column>

      <el-table-column
                label="目录"
                prop="catalog"
                >
              </el-table-column>

      <el-table-column
                label="题型" >
                <template slot-scope="scope">
                {{questionTypes(scope.row.questionType) }}
                </template>
      </el-table-column>

      <el-table-column
                width="280"
                label="提干"
                >
               <template slot-scope="scope">
               <span v-html="scope.row.question "></span>
               </template>
               </el-table-column >

      <el-table-column
               width="180"
               label="录入时间"
               prop="addDate"
               >
              </el-table-column>

      <el-table-column
              width="80"
              label="难度"
              prop="questionType">
              <template slot-scope="scope">
              {{formatType(scope.row.difficulty) }}
              </template>
              </el-table-column>

      <el-table-column
              width="120"
              label="录入人"
              prop="creator"
              >
              </el-table-column>

      <el-table-column
              width="120"
              label="审核状态"
              >
              <template slot-scope="scope">
              {{dooChkType(scope.row.chkState) }}
              </template>
              </el-table-column>

      <el-table-column
              width="150"
              label="审核意见"
              prop="chkRemarks"
              >
              </el-table-column>

      <el-table-column
              width="120"
              label="审核人"
              prop="chkUser"
              >
            </el-table-column>

       <el-table-column label="发布状态" width="150">

            <template slot-scope="scope">
            {{ publis(scope.row.publishState) }}
            </template>
            </el-table-column>

        <el-table-column  fixed="right" label="操作" width="200">
          <template slot-scope="scope">
             <!-- 预览 -->
             <el-button
             size="mini"
             type="text"
             @click="handlePreview(scope.$index, scope.row)"

             > 预览 </el-button>

            <el-button
                  :disabled="scope.row.chkState === 1 "
                  @click=" doaudit(scope.row.id) "
                  size="mini"
                  type="text"
            > 审核 </el-button>
            <el-button
                  size="mini"
                  @click="$router.push({path:'new',query: { aid: question.id}})"
                  type="text"
            > 修改 </el-button>
            <el-button
                  size="mini"
                  @click="choiceness(scope.row.publishState,scope.row.id)"
                  type="text"
            > {{ scope.row.publishState === 1 ? '下架' : '上架'  }}</el-button>

            <el-button
                  size="mini"
                  @click="doOpen(scope.row.id)"
                  type="text"
            > 删除</el-button>
          </template>
        </el-table-column>

 </el-table>

 <!-- 分页 -->
    <el-pagination
              background
              style="margin-top: 20px; text-align: right;"
              @current-change="handleCurrentChange"
              :current-page.sync="Render.page"
              :page-sizes="[5,10,20,50]"
              :page-size="Render.pagesize"
              :pager-count="5"
              layout="prev, pager, next,sizes, jumper"
              :total="total"
              >
     </el-pagination>

   <!-- 弹窗 -->
   <el-dialog

             title="题目预览"
             :visible.sync="dialogVisible"
             width="900px"
             :before-close="handleClose"
            >

     <el-descriptions
             class="margin-top"
             :column="4"
             >

          <el-descriptions-item label="【题型】">
                {{ questionTypes(preview.questionType) }}题
            </el-descriptions-item>

          <el-descriptions-item label="【编号】">
                {{ preview.id }}
            </el-descriptions-item>

          <el-descriptions-item label="【难度】">
              {{ formatType(preview.difficulty) }}
            </el-descriptions-item>

          <el-descriptions-item label="【标签】">
              {{ preview.tags}}
            </el-descriptions-item>

          <el-descriptions-item label="【学科】">
              {{ preview.subjectName }}
            </el-descriptions-item>

          <el-descriptions-item label="【目录】">
              {{ preview.directoryName}}
            </el-descriptions-item>

          <el-descriptions-item label="【方向】">
              {{ preview.direction}}
            </el-descriptions-item>

      </el-descriptions>

         <!-- 分割线 -->
         <el-divider ></el-divider>

       <span> 【题干】：</span>
       <div v-html="preview.question" style="color: blue;"></div>

       <el-form>

          <el-form-item >
            <div v-if="preview.questionType === '1'">单选题 选项：（以下选中的选项为正确答案）
            </div>
            <div v-if="preview.questionType === '2'">多选题 选项：（以下选中的选项为正确答案）
            </div>

            <el-radio-group
                v-model="radio"
                v-if="preview.questionType === '1'"
            >
           <template v-for="item in preview.options">
             <div :key="item.id">
               <el-radio class="radio" :label="item.isRight" >{{ item.title }}</el-radio>
             </div>
           </template>
         </el-radio-group>

         <el-checkbox-group
              v-else-if="preview.questionType === '2'"
              v-model="type"
              >
         <template v-for="item in preview.options">
             <div :key="item.id" style="padding: 0.2px 0px;">
                <el-checkbox class="radio"  :label="item.isRight" name="type">
                  {{ item.title }}
                </el-checkbox>
             </div>
         </template>

         </el-checkbox-group>

       </el-form-item>

     </el-form>

       <!-- 分割线 -->
       <el-divider ></el-divider>

       <el-descriptions
             class="margin-top"
             :column="1"
           >
             <el-descriptions-item label="【参考答案】">
                 <el-button type="danger" @click="flag = true">视频答案预览 </el-button>
                  </el-descriptions-item>
             </el-descriptions>

            <div style="width: 400px; height: 300px;" v-if="flag ">
              <video
                 style="width: 100%; height:100%;"
                 id="mse" autoplay=true playsinline controls="controls">
                 <source :src="preview.videoURL" type="video/mp4">
                 你的浏览器不支持Video标签
              </video>
            </div>

       <!-- 分割线 -->
       <el-divider ></el-divider>

       <el-descriptions
             class="margin-top"
             :column="1"
             >
             <el-descriptions-item label="【答案解析】">
                 {{ preview.remarks }}
             </el-descriptions-item>
       </el-descriptions>

       <!-- 分割线 -->
       <el-divider ></el-divider>

       <el-descriptions
             class="margin-top"
             :column="1"
           >
             <el-descriptions-item label="【题目备注】">
                  <span v-html="preview.answer"></span>
              </el-descriptions-item>
       </el-descriptions>

     <span slot="footer" class="dialog-footer">
       <el-button @click="dialogVisible = false">关闭</el-button>
     </span>
   </el-dialog>

   <!-- 审核弹框 -->
        <el-dialog
                  title="题目审核"
                  :visible.sync="dialogFormVisible"
                  width="400px"
                  right
          >
          <el-form :model="form" >
            <el-form-item >
              <el-radio-group v-model="chkState">
                <el-radio label= "1" >通过</el-radio>
                <el-radio label= "2" >拒绝</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入审核内容"
              v-model="TryToReview.chkRemarks">
            </el-input>

          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="hSubmit">确 定</el-button>
          </div>
      </el-dialog>

    </el-card>

</div>
</template>

<script>
import { list as SubjectList } from '@/api/hmmm/subjects.js'
import { list as directoryListing } from '@/api/hmmm/directorys.js'
import { list as Tags } from '@/api/hmmm/tags.js'
import { questionType, difficulty, direction, chkType, publishType } from '@/api/hmmm/constants.js'
import { list as user } from '@/api/base/users.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { choice as questionBank, detail as particulars, remove as deleteRole, choiceAdd as JoinToCancel, choicePublish as grounding, choiceCheck } from '@/api/hmmm/questions.js'
const hireType = difficulty.reduce((acc, item) => { return { ...acc, [item.value]: item.label } }, {})
const questionTypes = questionType.reduce((acc, item) => { return { ...acc, [item.value]: item.label } }, {})
// 审核状态
const doChkType = chkType.reduce((acc, item) => { return { ...acc, [item.value]: item.label } }, {})

const publis = publishType.reduce((acc, item) => { return { ...acc, [item.value]: item.label } }, {})
export default {
  data () {
    return {
      form: {
        subjectName: '', // 学科
        directoryName: '', // 二级目录
        tagName: '', // 标签
        question: '', // 关键字
        types: '', // 试题类型
        difficulty: '', // 难度
        direction: '', // 方向
        user: '', // 录入人
        TitleNotes: '', // 题目备注
        shortened: '', // 企业简介
        provinces: '', // 城市
        citys: '' // 城市下级
      },
      // 筛选
      Render: {
        page: 1,
        pagesize: 5
      },
      // 筛选区域渲染
      FiltrateRender: {
        Subject: [], // 学科
        Directory: [], // 二级目录
        Tags: [], // 标签
        questionType, // 试题类型
        difficulty, // 难度
        direction, // 方向
        user: [], // 录入人
        provinces: provinces(), // 城市
        citys: [] // 城市下级
      },

      total: 0,
      region: '',
      question: [],
      dialogVisible: false,
      flag: false,
      preview: {},
      radio: 1,
      type: [1],
      activeName: 'first',
      dialogFormVisible: false,

      TryToReview: {
        chkRemarks: '',
        id: ''
      },
      chkState: '1'
    }
  },
  async created () {
    // 学科列表
    const { data: { items: Subject } } = await SubjectList({ page: 1, pagesize: 20 })
    this.FiltrateRender.Subject = Subject
    // 用户列表
    const { data: { list } } = await user()
    this.FiltrateRender.user = list

    // 精选题库
    this.loadRoles()
  },
  methods: {

    async loadRoles () {
      try {
        const res = await questionBank(this.Render)
        this.question = res.data.items
        this.total = res.data.counts
      } catch (err) {
      }
    },
    handleCurrentChange (curPage) {
      this.Render.page = curPage
      this.loadRoles(this.Render)
    },
    // 清除
    resetForm (searchForm) {
      this.form.citys = ''
      this.$refs[searchForm].resetFields()
    },
    // 搜索
    async search () {
      //  form是查询条件

      // 备份下数据
      let arr = this.question
      // console.log(arr)

      // 通过key值循环处理
      Object.keys(this.form).forEach(e => {
        // 调用自己定义好的筛选方法
        arr = this.filterFunc(this.form[e], e, this.question)
      })
      // 为表格赋值
      this.question = arr
    },
    // val: 查询条件的值
    // target: 目标参数，就是你这个值对应的key
    // filterarr: 被筛选的数组
    filterFunc (val, target, filterArr) {
      console.log('11111', filterArr)
      if (val === undefined || val === '') return filterArr
      // console.log(val)
      console.log(target)

      return filterArr.filter(p => p[target].indexOf(val) > -1)
    },
    // 关闭弹框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    // 预览
    async handlePreview (index, row) {
      this.dialogVisible = true
      const src = await particulars({ id: row.id })
      this.preview = src.data
    },
    formatType (typeId) {
      return hireType[typeId]
    },
    questionTypes (typeId) {
      return questionTypes[typeId]
    },
    dooChkType (typeId) {
      return doChkType[typeId]
    },
    publis (typeId) {
      return publis[typeId]
    },
    // 删除
    async doDelete (id) {
      try {
        await deleteRole({ id })
        this.$message.success('删除成功')
        if (this.question.length === 1) {
          this.Render.page--
          this.Render.page = Math.max(1, this.Render.page)
        }
        this.loadRoles()
      } catch (err) {
        this.$message.error('删除失败')
      }
    },
    // 删除提示
    doOpen (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDelete(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已经取消删除'
        })
      })
    },
    async Join (data) {
      try {
        await JoinToCancel(data)
        this.$message.success('加入成功')
        this.loadRoles()
      } catch (err) {
        this.$message.error('加入失败')
      }
    },
    // 加入或移除精品题库
    choiceness (row, id) {
      this.$confirm(`您确认${row === 2 ? '上架' : '下架'}这道题目吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(async () => {
        const publishState = row === 1 ? 0 : 1
        await grounding({ publishState, id })
        this.loadRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已经取消'
        })
      })
    },
    async handleClick (tab, event) {
      // console.log(tab, event)
      if (tab.name === 'first') {
        await this.loadRoles()
      } else if (tab.name === 'second') {
        await this.loadRoles()
        this.question = this.question.filter(item => item.chkState === 0)
      } else if (tab.name === 'third') {
        await this.loadRoles()
        this.question = this.question.filter(item => item.chkState === 1)
      } else if (tab.name === 'fourth') {
        await this.loadRoles()
        this.question = this.question.filter(item => item.chkState === 2)
      }
    },
    doaudit (id) {
      this.dialogFormVisible = true
      this.TryToReview.id = id
    },
    // 题目审核 确定
    async hSubmit () {
      if (this.TryToReview.chkRemarks === '') {
        return this.$message({
          message: '请输入审核内容',
          type: 'warning'
        })
      }
      // const res = await review(this.TryToReview)
      await choiceCheck({ ...this.TryToReview, chkState: +this.chkState })
      this.dialogFormVisible = false
      this.loadRoles()
    }
  },
  watch: {
    'form.subjectName': {
      deep: true,
      async handler (newVal, oldVal) {
        if (newVal) {
          // 二级目录
          this.form.directory = ''
          this.form.Tags = ''
          // 目录列表
          const { data: { items } } = await directoryListing()
          // 筛选当前对应的目录
          this.FiltrateRender.Directory = items.filter(item => item.subjectName === newVal)
          // 标签
          const { data: { items: res } } = await Tags()
          // 筛选当前对应的标签
          this.FiltrateRender.Tags = res.filter(item => item.subjectName === newVal)
        }
      }
    },
    'form.provinces': {
      deep: true,
      async handler (newVal, oldVal) {
        if (newVal) {
          this.form.citys = ''
          this.FiltrateRender.citys = await citys(newVal)
        }
      }
    }
  }

}
</script>

<style lang="scss" scoped >

.container {
 // height: 100vh;
 // overflow-x: hidden;
 .row-bg {
   margin-bottom: 15px;
 }
 .form-select {
   width: 100%;
 ::v-deep .el-select-dropdown__item.selected {
   background: pink;
 }

}

}
::v-deep .el-select-dropdown__empty{
 margin: 0;
 padding: 10px 0;
 height: 38px;
 text-align: center;
 line-height: 1;
}
.el-divider--horizontal{
 margin: 2px 0;
}
::v-deep .radio{
      display: block;
      margin:10px 0;
   }
</style>
